﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IndustrialSmokeCalc.SmokeCalcWCF;

namespace IndustrialSmokeCalc
{
    public partial class Benchmark : PhoneApplicationPage
    {
        private double[] value;

        public Benchmark()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GetOpacityStatistic();
        }

        private void GetOpacityStatistic()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetOpacityStatisticCompleted += GetOpacityStatisticCompleted;
            client.GetOpacityStatisticAsync();
        }

        private void SetBenchmarkValue(double[] value)
        {
            double topHighest = CalculateTopMargin(chart.radChart.ActualHeight, value[0]);
            chart.lineHighest.Margin = new Thickness(43, 12 + topHighest, 0, 0);
            chart.lineHighest.Visibility = Visibility.Visible;

            double topAverage = CalculateTopMargin(chart.radChart.ActualHeight, value[2]);
            chart.lineAverage.Margin = new Thickness(43, 12 + topAverage, 0, 0);
            chart.lineAverage.Visibility = Visibility.Visible;

            double topLowest = CalculateTopMargin(chart.radChart.ActualHeight, value[1]);
            chart.lineLowest.Margin = new Thickness(43, 12 + topLowest, 0, 0);
            chart.lineLowest.Visibility = Visibility.Visible;
        }

        private double CalculateTopMargin(double height, double val)
        {
            return (height - 23.0) / 100.0 * (100.0 - val);
        }

        private void GetOpacityStatisticCompleted(object sender, GetOpacityStatisticCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
                NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
            }
            else if(e.Result != null)
            {
                value = new double[]{e.Result[0], e.Result[1], e.Result[2]};
                SetBenchmarkValue(value);
            }
        }
    }
}